package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.usian.admin.mapper.LoginMapper;
import com.usian.admin.service.LoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.ext.IBM037;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginMapper loginMapper;
    @Override
    public ResponseResult addUser( AdUser adUser) {
//        if (apUser==null){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//        }
//        获取用户输入的密码
        String password = adUser.getPassword();
        String gensalt = BCrypt.gensalt();
        String newpwd = BCrypt.hashpw(password, gensalt);
        adUser.setPassword(newpwd);
        adUser.setSalt(gensalt);
        loginMapper.insert(adUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
//        判断用户名或者密码是否为空

        QueryWrapper<AdUser> qw = new QueryWrapper<>();
        qw.eq("name",adUserDto.getName());
        AdUser adUser = loginMapper.selectOne(qw);
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名不存在");
        }
//        if (!adUserDto.getName().equals(adUser.getName())){
//            return ResponseResult.errorResult(5,"用户名错误");
//        }
        if (!BCrypt.checkpw(adUserDto.getPassword(),adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",adUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
